package com.bonc.test.redisdemo.ctrl;

import java.util.List;

import javax.persistence.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.bonc.test.redisdemo.dao.CustomerDao;
import com.bonc.test.redisdemo.entity.Address;
import com.bonc.test.redisdemo.entity.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

	private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);
	
	@Autowired
	private CustomerDao customerDao;
	
	@Autowired
	EntityManager entityManager;
	
	@RequestMapping(value="/add")
	@ResponseBody
	public String add(){
		Customer eo = new Customer();
		Address address = new Address();
		address.setAddress("南京市");
		eo.setName("mingzhi");
		eo.setAddress(address);//把地址存到eo的属性里，eo存的时候就会把数据存到两个表里。
		customerDao.save(eo);
		return "200";
	}
	
	//级联查询方法1 		使用JPA查询
	@RequestMapping(value = {"/find1/{id}"}, method = RequestMethod.GET)
	@ResponseBody
    public Customer find1(@PathVariable long id) {
		return customerDao.findOne(id);//查询的时候自动级联查询，查id=1的用户信息会把地址信息带出来。
    }
	
	//级联查询方法2 		使用@Query
	@RequestMapping(value = {"/find2/{id}"}, method = RequestMethod.GET)
	@ResponseBody
    public String find2(@PathVariable long id) {
		return customerDao.findInfo(id);//点击findInfo这个自定义方法可以实现
    }
	
	//级联查询方法3			使用原生sql
	@RequestMapping(value = {"/find3/{id}"}, method = RequestMethod.GET)
	@ResponseBody
    public String find3(@PathVariable long id) {
		String sql = "select c.name,a.address from customer c join address a on c.address_id = a.id where c.id='1';";
		List objecArraytList = entityManager.createNativeQuery(sql).getResultList();//查询返回的是list用这个
//		Object object = entityManager.createNativeQuery(sql).getSingleResult();//查询返回的是object用这个
		return JSON.toJSONString(objecArraytList);
    }
}
